package org.jeecg.modules.oms.service.impl;

import org.jeecg.modules.oms.entity.OmsInquiry;
import org.jeecg.modules.oms.entity.OmsInquiryItem;
import org.jeecg.modules.oms.mapper.OmsInquiryMapper;
import org.jeecg.modules.oms.service.IOmsInquiryService;
import org.jeecg.modules.oms.service.IOmsInquiryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;

/**
 * @Description: 询单表
 * @Author: jeecg-boot
 * @Date: 2025-09-29
 * @Version: V1.0
 */
@Service
public class OmsInquiryServiceImpl extends ServiceImpl<OmsInquiryMapper, OmsInquiry> implements IOmsInquiryService {

    @Autowired
    private IOmsInquiryItemService omsInquiryItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInquiryWithItems(OmsInquiry inquiry) {
        // 设置询单日期
        if (inquiry.getInquiryDate() == null) {
            inquiry.setInquiryDate(new Date());
        }
        
        // 设置默认状态为待处理
        if (inquiry.getStatus() == null) {
            inquiry.setStatus(0);
        }
        
        // 保存询单主表
        boolean result = this.save(inquiry);
        
        // 如果有询单明细，保存明细
        if (result && inquiry.getItems() != null && !inquiry.getItems().isEmpty()) {
            List<OmsInquiryItem> items = inquiry.getItems();
            for (OmsInquiryItem item : items) {
                item.setInquiryId(inquiry.getId());
            }
            result = omsInquiryItemService.saveBatch(items);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInquiryWithItems(OmsInquiry inquiry) {
        // 更新询单主表
        boolean result = this.updateById(inquiry);
        
        if (result && inquiry.getItems() != null) {
            // 先删除原有明细
            omsInquiryItemService.deleteByInquiryId(inquiry.getId());
            
            // 保存新的明细
            if (!inquiry.getItems().isEmpty()) {
                List<OmsInquiryItem> items = inquiry.getItems();
                for (OmsInquiryItem item : items) {
                    item.setInquiryId(inquiry.getId());
                    item.setId(null); // 重新生成ID
                }
                result = omsInquiryItemService.saveBatch(items);
            }
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteInquiryWithItems(String id) {
        // 删除询单明细
        omsInquiryItemService.deleteByInquiryId(id);
        
        // 删除询单主表
        return this.removeById(id);
    }

}
